import { createRouter, createWebHistory, type RouteRecordRaw, type RouteLocationNormalized, type NavigationGuardNext } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import UserManagementView from '../views/UserManagementView.vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: {
      requiresAuth: false,
      hideForAuth: true
    }
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView,
    meta: {
      requiresAuth: false,
      hideForAuth: true
    }
  },
  {
    path: '/users',
    name: 'user-management',
    component: UserManagementView,
    meta: {
      requiresAuth: true,
      requiresAdmin: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL || ''),
  routes
})

// 路由守卫
router.beforeEach((to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
  // 检查是否存在token来确定认证状态
  const token = localStorage.getItem('token')
  const isAuthenticated = !!token
  const userInfo = localStorage.getItem('userInfo')
  const user = userInfo ? JSON.parse(userInfo) : null
  const isAdmin = user && user.roles && user.roles.includes('ROLE_ADMIN')

  // 如果需要认证但未登录，重定向到登录页面
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  }
  // 如果已登录且尝试访问登录/注册页面，重定向到首页
  else if (to.meta.hideForAuth && isAuthenticated) {
    next('/')
  }
  // 如果需要管理员权限但不是管理员，重定向到首页
  else if (to.meta.requiresAdmin && !isAdmin) {
    next('/')
  }
  else {
    next()
  }
})

export default router